<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2018/5/30
 * Time: 下午1:51
 */

namespace App\Http\Controllers\Api\Shop;



use App\Http\Controllers\Controller;

use App\Libs\Pay\WechatPay;
use App\Modules\Home\Services\CategoryService;
use App\Modules\Order\Services\OrderService;
use App\Modules\Shop\Models\GoodsCategories;
use App\Modules\Shop\Services\CartService;
use App\Modules\Shop\Services\CouponService;
use App\Modules\Shop\Services\GoodsCategoriesService;
use App\Modules\Shop\Services\OrderProductsService;
use App\Modules\Shop\Services\ProductsService;
use App\Modules\Shop\Services\ProductsSpecifictionService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use phpDocumentor\Reflection\Types\Mixed_;

class ProductsController extends Controller
{
    /**
     * 商品列表
     * @param Request $request
     * @return mixed
     */
    public function goodsList(Request $request) {
        $goods_name = $request->input('product_name','');
        $category_id = $request->input('category_id','');
        $param = [];
        if($goods_name) {
           $param['product_name'] = $goods_name;
        }
        if($category_id) {
            $param['category_id'] = $category_id;
        }
        $res = ProductsService::getProductsList($param);
        foreach ($res as $item){
            $product_specs = $item->product_specific;
            //$price_high=$product_specs[0]->price;
            $price_low = $product_specs[0]->price;
            $market_price_low = $product_specs[0]->origin_price;
            $thumb = env('APP_DOMAIN').$item->img_thum;
            $item->img_thum = $thumb;
            foreach ($product_specs as $key=>$product_spec) {
                //$price_high = ($product_spec->price >$price_high)?$product_spec->price : $price_high;
                $price_low  = ($product_spec->price <$price_low)?$product_spec->price : $price_low;
                $market_price_low = ($product_spec->origin_price <$market_price_low)?$product_spec->origin_price : $market_price_low;
                //$item->price = ($price_high == $price_low)?$price_high:$price_low.'-'.$price_high;
                //$item->market_price = $product_spec->origin_price;
            }
            $item->price = $price_low;
            //var_dump($item->category);
            $item->is_vip_product = ($item->category->id==1)?1:0;
            $item->market_price = $market_price_low;
        }
        return response()->pagination($res);
    }

    /**
     * 商品详情
     * @param Request $request
     * @return mixed
     */
    public function goods_detail(Request $request) {
        $goods_id = $request->input('product_id','');
        if(empty($goods_id)) {
            return response()->error('PARAM_EMPTY');
        }
        $res = ProductsService::getProductsDetail($goods_id);
        $img_arr = explode(',',$res->images);
        array_walk($img_arr,function (&$arr,$key){
            $arr= env('APP_DOMAIN').$arr;
        });
        $res->images = $img_arr;
        $res->detail = explode(',',$res->detail);
        $res->img_thum = env('APP_DOMAIN').$res->img_thum;
        $res->product_specific=$res->product_specific()->orderBy('price')->get();
        $res->ship_fee_template;
        $res->is_vip_product = ($res->category->id == 1)?1:0;
        return response()->success($res);
    }

    /**
     * 添加到购物车
     * @param Request $request
     * @return mixed
     */
    public function addToCart(Request $request) {
        $uid = $this->getLoginUserId();
        $goods_id = $request->input('product_id','');
        $goods_spec_id = $request->input('product_spec_id','');
        $count = $request->input('count','');
        if(empty($goods_id) || empty($count) || empty($goods_spec_id)) {
            return response()->error('PARAM_EMPTY');
        }
        $cart_goods = CartService::getByProductSpecIdAndUid($goods_spec_id,$uid);
        if($cart_goods) {
            $cart_goods->count = $cart_goods->count + $count;
            $cart_goods->save();
        }else{
            CartService::addOne(['uid'=>$uid,'product_id'=>$goods_id,'count'=>$count,'product_spec_id'=>$goods_spec_id]);
        }
        return response()->success();
    }

    /**
     * @param Request $request
     * @return Mixed
     */
    public function removeFromCart(Request $request) {
        $uid = $this->getLoginUserId();
        $goods_spec_id = $request->input('product_spec_id','');
        //$count = $request->input('count','');
        if(empty($goods_spec_id)) {
            return response()->error('PARAM_EMPTY');
        }

        CartService::DecreaseGoodsByUidAndSpecId($goods_spec_id,$uid);
        return response()->success();
    }

    /**
     * 获取购物车列表
     * @param Request $request
     * @return mixed
     */
    public function getCartList(Request $request) {
        $uid = $this->getLoginUserId();
        $cart_list = CartService::getCartListByUid($uid);
        foreach ($cart_list as $cart) {
            $cart->product = $cart->products()->select('id','product_name','img_thum','images','category_id','ship_fee_temp')->first();
            $cart->product->img_thum = env('APP_DOMAIN').$cart->product->img_thum;
            $cart_imgs_arr = explode(',',$cart->product->images);
            array_walk($cart_imgs_arr,function(&$arr,$key) {
                $arr= env('APP_DOMAIN').$arr;
            });
            $cart->product->images  =$cart_imgs_arr;
            $cart->product->ship_fee_template;
            $cart->is_vip_product = $cart->product->category->id==1?1:0;
            $cart->product_specific = $cart->product_specific()->select('price','origin_price','specification','cost')->first();
        }
        return response()->pagination($cart_list);
    }

    /**
     * 获取商品分类列表
     * @param Request $request
     * @return mixed
     */
    public function getCategories(Request $request) {
        $categories = GoodsCategoriesService::getAll();
        $loop = config('shops.loop_imgs');
        $res = compact('categories','loop');
        return response()->success($res);
    }

    /**
     * 获取购物车商品数量
     * @return mixed
     */
    public function getCartGoodsNum() {
        $uid = $this->getLoginUserId();
        $cart_goods_num = CartService::getUserCartNum($uid);
        return response()->success($cart_goods_num);
    }

    /**
     * 购物车批量删除
     * @param Request $request
     * @return mixed
     */
    public function mutiDeleteCarts(Request $request) {
        $cart_id_list = $request->input('cart_ids','');
        $uid = $this->getLoginUserId();
        if(empty($cart_id_list)) {
            return response()->error('PARAM_EMPTY');
        }
        \DB::beginTransaction();
        try{
            $carts = CartService::getListByIds(explode(',',$cart_id_list));
            foreach ($carts as $cart) {
                if($cart->uid != $uid) {
                    \DB::rollBack();
                    return response()->error('PARAM_ERROR');
                }
                $cart->delete();
            }
            \DB::commit();
        }catch (\Exception $exception) {
            \DB::rollBack();
            \Log::error(__FUNCTION__.':error:'.$uid.':'.$exception->getMessage());
            return response()->error('DELETE_FAILURE');
        }
        return response()->success();
    }
}